package com.wedu.modules.dss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.wedu.common.utils.PageUtils;
import com.wedu.common.utils.Query;
import com.wedu.modules.dss.dao.DssDeviceInformationDao;
import com.wedu.modules.dss.entity.DssDeviceInformationEntity;
import com.wedu.modules.dss.entity.DssFollowEntity;
import com.wedu.modules.dss.entity.DssOperationStatusEntity;
import com.wedu.modules.dss.entity.dto.DssDeviceInformationDTO;
import com.wedu.modules.dss.service.DssDeviceInformationService;
import com.wedu.modules.sys.dao.SysDictDao;
import com.wedu.modules.sys.dao.SysUserDao;
import com.wedu.modules.sys.entity.GameEntity;
import com.wedu.modules.sys.entity.SysDictEntity;
import com.wedu.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 主表，设备信息表 服务实现类
 * </p>
 *
 * @author jdw
 * @since 2025-03-06
 */
@Service
public class DssDeviceInformationServiceImpl extends ServiceImpl<DssDeviceInformationDao, DssDeviceInformationEntity> implements DssDeviceInformationService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysDictDao sysDictDao;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return "上传失败，因为文件是空的。";
        }

        // 获取文件名和保存路径
        String fileName = file.getOriginalFilename();
        String filePath = "D:/分享课程/uploads/"; // 自定义文件保存路径
        File dest = new File(filePath + fileName);

        // 确保目录存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        // 保存文件
        try {
            file.transferTo(dest);
            return "文件上传成功：" + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败。";
        }
    }
    @Override
    public HashMap<String, Object> dictAndUserQuery(DssDeviceInformationDTO dssDeviceInformationDTO) {
        QueryWrapper<SysDictEntity> dictQueryWrapper=new QueryWrapper<>();
        dictQueryWrapper.eq("name",dssDeviceInformationDTO.getName());
        SysDictEntity dict = sysDictDao.selectOne(dictQueryWrapper);
        QueryWrapper<SysUserEntity> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("real_name",dssDeviceInformationDTO.getRealName());
        SysUserEntity user = sysUserDao.selectOne(userQueryWrapper);
        HashMap<String,Object> map=new HashMap<>();
        map.put("type",dict.getValue());
        map.put("userId",user.getUserId());
        return map;
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params, Long userId) {
        String lightStatus = (String) params.get("lightStatus");
        int light=0;
        if (StringUtils.isNotBlank(lightStatus )) {
            if (lightStatus.equals("1")) {
                light = 1;
            } else if (lightStatus.equals("0")) {
                light = 0;
            } else if (lightStatus.equals("-1")) {
                light = -1;
            }
        }
        String selectedFilter = (String)params.get("selectedFilter");

        boolean oneYearAgo=false;
        boolean threeYearsAgo=false;
        boolean threeYearsLater=false;
        if (StringUtils.isNotBlank(selectedFilter)) {
            if (selectedFilter.equals("一年以内")) {
                oneYearAgo = true;
            } else if (selectedFilter.equals("超过1年但小于等于3年")) {
                threeYearsAgo = true;
            } else if (selectedFilter.equals("三年以后")) {
                threeYearsLater = true;
            }
        }
        String select = (String)params.get("select");
        String deviceId = null;
        String deviceName = null;
        String deviceModel = null;
        String deviceInformation = (String)params.get("deviceInformation");
        if (StringUtils.isNotBlank(select)) {
        if (select.equals("deviceId")){
             deviceId =select;
        }else if (select.equals("deviceName")){
             deviceName =select;
        }else if (select.equals("deviceModel")){
            deviceModel =select;
        }  }
        MPJLambdaWrapper<DssDeviceInformationEntity> wrapper = new MPJLambdaWrapper<DssDeviceInformationEntity>()
                .selectAll(DssDeviceInformationEntity.class)//查询全部字段
                .select(SysDictEntity::getName)
                .select(SysUserEntity::getRealName)
                .select(DssOperationStatusEntity::getLightStatus)
                .selectAs(DssFollowEntity::getId,DssDeviceInformationDTO::getFollowId)
                .leftJoin(SysDictEntity.class, SysDictEntity::getValue, DssDeviceInformationEntity::getDeviceType)
                .leftJoin(DssOperationStatusEntity.class, on -> on
                        .eq(DssOperationStatusEntity::getDeviceId, DssDeviceInformationEntity::getId)
                        .isNull(DssOperationStatusEntity::getLightOver)  // 关键过滤条件
                )
                .leftJoin(SysUserEntity.class, on -> on
                        .eq(SysUserEntity::getUserId, DssDeviceInformationEntity::getCreateBy))
                .leftJoin(DssFollowEntity.class, on -> on
                        .eq(DssFollowEntity::getDeviceId, DssDeviceInformationEntity::getDeviceId)
                          .eq(DssFollowEntity::getUserId,userId)// 关键过滤条件
                )
               // .isNotNull(DssOperationStatusEntity::getLightOver)  // 结束亮灯时间为空lightStatus
             //   .isNotNull(DssOperationStatusEntity::getLightStart)
                .eq(StringUtils.isNotBlank(lightStatus),"light_status", light)
                .like(StringUtils.isNotBlank(deviceInformation ) && StringUtils.isNotBlank(deviceId),"t.device_id", deviceInformation)
                .like(StringUtils.isNotBlank(deviceInformation)&&StringUtils.isNotBlank(deviceName),"device_name", deviceInformation)
                .like(StringUtils.isNotBlank(deviceInformation)&&StringUtils.isNotBlank(deviceModel),"device_model", deviceInformation)
                .eq(SysDictEntity::getCode,"deviceType")


                .ge(oneYearAgo,"produce_time", LocalDate.now().minusYears(1))// 近一年（含当天）

                .lt(threeYearsLater,"produce_time", LocalDate.now().minusYears(3))// 三年后（早于3年前）

                .lt(threeYearsAgo,"produce_time", LocalDate.now().minusYears(1))// 超过1年但≤3年
                .ge(threeYearsAgo,"produce_time", LocalDate.now().minusYears(3));

        IPage<DssDeviceInformationEntity> dssDeviceInformationPage = this.page(
                new Query<DssDeviceInformationEntity>().getPage(params), wrapper);
        IPage<DssDeviceInformationDTO> page =new Page<>();
        page.setTotal(dssDeviceInformationPage.getTotal());
        page.setSize(dssDeviceInformationPage.getSize());
        //  page.setRecords(dssDeviceInformationList);
        page.setPages(dssDeviceInformationPage.getPages());
        page.setCurrent(dssDeviceInformationPage.getCurrent());
        IPage<DssDeviceInformationDTO> dssDeviceInformationDAOPage = baseMapper.selectJoinPage(page,DssDeviceInformationDTO.class, wrapper);





        return new PageUtils(dssDeviceInformationDAOPage );
    }

    @Override
    public Map<String, Object> queryChildPage() {
        QueryWrapper<SysDictEntity>  dictQueryWrapper=new QueryWrapper<>();
        dictQueryWrapper
                .orderByAsc("sort")
                .eq("type", "2");//查询游戏类型字典选项列表

        List<SysDictEntity> deviceDictList = sysDictDao.selectList(dictQueryWrapper);
        List<SysDictEntity> deviceTypeList =new ArrayList<>();

        Map<String, Object> dictMap = new HashMap<>();

        for (SysDictEntity dictEntity : deviceDictList) {
            if (dictEntity.getCode().equals("deviceType")){
                deviceTypeList.add(dictEntity);
            }
        }

        dictMap.put("deviceTypeList",deviceTypeList);
     //   dictMap.put("ageGroupList",ageGroupList);
        return dictMap;
    }
    @Override
    public void saveWarning(DssDeviceInformationEntity deviceInformation) {
        //添加所选方案与设备id，根据方案添加时间，如：方案一保养时间为当前+15天，预警时间为当前时间+12天
        //获取前端选择的主表中的设备id

        //查询M表中的id字段
        QueryWrapper<DssDeviceInformationEntity> wrapper = new QueryWrapper<DssDeviceInformationEntity>();
        List<DssDeviceInformationEntity> list = baseMapper.selectList(wrapper);
        List<String> deviceIdlist = new ArrayList<>();
        //获取他的保养剂计划
        String maintenancePlan = deviceInformation.getMaintenancePlan();
        for (DssDeviceInformationEntity warningEntity : list) {
            deviceIdlist.add(warningEntity.getDeviceId());
        }

            if (maintenancePlan.equals("1")){//如果方案一：当前时间+X天 预警时间+(X-Y)天 X=15 Y=3
                Integer x = deviceInformation.getMaintenanceCycle();
                Integer y = deviceInformation.getAdvanceTime();
                Date date1 = new Date();
                Calendar calendar1 = Calendar.getInstance();
                calendar1.add(Calendar.DATE,x);/***/
                date1 = calendar1.getTime();
                deviceInformation.setMaintenanceDueTime(date1);
                Date date2 = new Date();
                Calendar calendar2 = Calendar.getInstance();
                calendar2.add(Calendar.DATE,(x-y));/***/
                date2 = calendar2.getTime();
                deviceInformation.setNoticeTime(date2);
                Date now = new Date();
                if (now.before(date2)){
                    deviceInformation.setMaintenanceStatus(1);
                }else if (now.after(date2)){
                    deviceInformation.setMaintenanceStatus(0);
                }else {
                    deviceInformation.setMaintenanceStatus(-1);
                }

            }else if (maintenancePlan.equals("2")){
                //如果方案二：当前时间+X小时  X=120
                Integer x = deviceInformation.getMaintenanceCycle();
                Date date3 = new Date();
                Calendar calendar3 = Calendar.getInstance();
                calendar3.add(Calendar.HOUR,x);/***/
                date3 = calendar3.getTime();
                deviceInformation.setMaintenanceDueTime(date3);
                deviceInformation.setNoticeTime(date3);
                Date now = new Date();
                if (now.before(date3)){
                    deviceInformation.setMaintenanceStatus(1);
                }else if (now.after(date3)){
                    deviceInformation.setMaintenanceStatus(0);
                }else {
                    deviceInformation.setMaintenanceStatus(-1);

                }
            }
            this.save(deviceInformation);


    }


}
